<!-- 订单管理-客户订单-销售订单 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div class="sales-order">
    <a-tabs v-model="getListType" @change="getSearchType" type="line">
      <a-tab-pane :key="1" title="全部销售订单"> </a-tab-pane>
      <a-tab-pane :key="2" title="我的销售订单"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-search
          search-button
          v-model="NumberSearch"
          :style="{ width: '220px' }"
          placeholder="订单号"
          @change="Search"
        />
        <a-input-search
          search-button
          v-model="clientCompanyNameVal"
          :style="{ width: '220px' }"
          placeholder="客户"
          @change="Search"
        />
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning" @click="OrderDerive">
          <template #icon>
            <icon-export :rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <TableTurn :table-data="getData" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :title="item.name"
        :data-index="item.code"
        :key="item.code"
        :width="200"
        align="center"
      >
        <!-- 计划开始时间 -->
        <template v-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <!-- 计划开始时间 -->
        <template v-else-if="item.code === 'totalPrice'" #cell="{ record }">
          ￥{{ record.totalPrice }}
        </template>

        <!-- 订单确认状态 -->
        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <div class="use-state">
            <div
              class="cycle"
              :class="
                record.state === 1 ? 'greyColor-cycle' : 'greenColor-cycle'
              "
            >
            </div>
            <div :class="record.state === 1 ? 'greyColor' : 'greenColor'">{{
              record.state === 1 ? '待确认' : '已确认'
            }}</div>
          </div>
        </template>

        <!-- 订单执行状态 -->
        <template v-else-if="item.code === 'executionState'" #cell="{}">
          <div class="use-state">
            <div class="cycle" :class="'greyColor-cycle'"> </div>
            <div :class="'greyColor'">{{ '待确认' }}</div>
          </div>
        </template>
      </a-table-column>

      <a-table-column :width="300" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <!-- <a-button
            v-if="record.state === 1"
            type="text"
            :style="{
              backgroundColor: '#31C27C',
              color: '#fff',
            }"
            @click="affirm(record, 1)"
            >确认</a-button
          > -->
          <!-- <a-button
              v-if="record.okState === 1"
              type="text"
              @click="goDetail(record.id, record.okState)"
              >订单详情</a-button
            > -->
          <a-button
            v-if="record.state === 1"
            type="text"
            @click="goDetail(record.id, record.state)"
            >订单详情</a-button
          >
          <a-popconfirm
            v-if="record.state === 1"
            @ok="deleteItem(record.id)"
            content="确定删除吗"
            type="error"
          >
            <a-button
              type="text"
              :style="{
                color: 'red',
              }"
              >删除</a-button
            >
          </a-popconfirm>

          <a-tooltip v-if="record.state !== 1" content="档案">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetail(record.id, record.state)"
            />
          </a-tooltip>
          <!-- <a-button v-if="record.state !== 1 && record.state !== 4" type="text"
            >变更</a-button
          >
          <a-button
            v-if="record.state === 2 && record.state !== 1"
            type="text"
            status="warning"
            @click="putOrderState(record, 3)"
          >
            挂起
          </a-button>
          <a-button
            v-if="record.state === 3 && record.state !== 1"
            type="text"
            @click="putOrderState(record, 2)"
          >
            执行
          </a-button> -->
          <a-popconfirm
            v-if="record.state !== 1 && record.state !== 4"
            @ok="stop(record)"
            content="确定终止订单吗"
            type="error"
          >
            <a-button
              type="text"
              :style="{
                color: 'red',
              }"
              >订单终止</a-button
            >
          </a-popconfirm>
        </template>
      </a-table-column>
    </TableTurn>
  </div>
  <FormHeaderSetting
    title="已完成订单列表表头设置"
    v-model:visible="formHeaderSettingVisible"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    GetClientOrder,
    GetHeaderSettings,
    putHeaderSettings,
    putClientOrder,
    DeleteClientOrder,
    GetOrderDeriveExcel,
  } from '@/api/order-management/client-order';

  const NumberSearch = ref();
  const clientCompanyNameVal = ref();
  const StateVal = ref();
  const router = useRouter();
  const title: string = '已完成订单';
  const breadCrumb: string[] = ['订单管理', '客户订单', '已完成订单'];
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  const modelCauseVisible = ref(false);

  const userState = ref(); // 储存状态数据
  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });
  const getListType = ref(1);

  // 新建销售订单
  const add = () => {
    router.push({
      name: 'SalesOrderAdd',
    });
  };

  // 获取对应列表信息
  const getData = async (pageData?: any) => {
    try {
      let msg: any = {};
      if (NumberSearch.value) msg.number = NumberSearch.value;
      if (clientCompanyNameVal.value)
        msg.clientCompanyName = clientCompanyNameVal.value;
      if (StateVal.value) msg.state = StateVal.value;

      const res = await GetClientOrder({
        ...pageData,
        ...msg,
        state: 4,
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // // 修改对应的订单状态列表
  // const searchState = (key: number) => {
  //   userState.value = key;
  //   tableRef.value.loadData();
  // };

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const Search = () => {
    tableRef.value.loadData();
  };

  // 重置按钮
  const reset = () => {
    NumberSearch.value = '';
    clientCompanyNameVal.value = '';
    StateVal.value = '';
    tableRef.value.loadData();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        listType: getListType.value,
        extend: JSON.stringify(val),
      };
      await putHeaderSettings(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const affirm = (record: any, key: number) => {
    router.push({
      name: 'SalesOrderDetail',
      query: {
        id: record.id,
        key,
      },
    });
  };

  // 前往订单详情或者订单档案
  const goDetail = (id: any, state: number) => {
    // 前往订单详情
    if (state === 1) {
      router.push({
        name: 'SalesOrderDetail',
        query: {
          id,
        },
      });
    }
    // 前往订单档案
    else {
      router.push({
        name: 'SalesFileDetail',
        query: {
          id,
        },
      });
    }
  };

  const columns = [
    {
      name: '销售订单编号',
      code: 'number',
      isDefault: 1,
    },
    {
      name: '客户名称',
      code: 'clientCompanyName',
      isDefault: 1,
    },
    {
      name: '客户联系人',
      code: 'customerName',
      isDefault: 1,
    },
    {
      name: '客户联系电话',
      code: 'customerPhone',
      isDefault: 1,
    },
    {
      name: '业务员',
      code: 'userStaffName',
      isDefault: 1,
    },
    {
      name: '订单总金额',
      code: 'totalPrice',
      isDefault: 1,
    },
    {
      name: '订单创建时间',
      code: 'createdAt',
      isDefault: 1,
    },

    {
      name: '关联需求编号',
      code: 'demandNumber',
      isDefault: 1,
    },

    // {
    //   name: '订单确认状态',
    //   code: 'okState',
    //   isDefault: 1,
    // },
    // {
    //   name: '订单执行状态',
    //   code: 'executionState',
    //   isDefault: 1,
    // },
  ];

  // 获取表头数据
  const headerSettingData = async (listType = 1) => {
    try {
      const res = await GetHeaderSettings({ listType });
      if (res.extends !== null) {
        headerSetting.list = res.extends;
      } else {
        headerSetting.list = columns;
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const getSearchType = (key: any) => {
    getListType.value = key;
    headerSettingData(key);
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];

    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const putOrderState = async (record: any, key: number) => {
    record.state = key;
    await putClientOrder(record);
    tableRef.value.loadData();
  };

  const stop = async (record: any) => {
    record.state = 4;
    await putClientOrder(record);
    tableRef.value.loadData();
  };

  const deleteItem = async (id: number) => {
    await DeleteClientOrder({ id });
    tableRef.value.loadData();
  };

  const OrderDerive = async () => {
    GetOrderDeriveExcel();
  };
</script>

<style scoped lang="less">
  // .sales-order {
  // }

  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  // .search-item {
  //   margin-top: 10px;
  // }

  .use-state {
    display: flex;
    justify-content: center;
    text-align: center;
    .cycle {
      position: relative;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      content: '';
      display: inline-block;
      top: 3px;
      right: 10px;
    }
  }

  // 待提交、待审核、已完成
  .greyColor {
    color: #c9cdd4;
  }
  .greyColor-cycle {
    background-color: #c9cdd4;
  }

  // 审核中、执行中
  .blueColor {
    color: #156dff;
  }
  .blueColor-cycle {
    background-color: #156dff;
  }

  // 已通过
  .greenColor {
    color: #31c273;
  }
  .greenColor-cycle {
    background-color: #31c273;
  }

  // 不通过
  .orangeColor {
    color: #fc6;
  }
  .orangeColor-cycle {
    background-color: #fc6;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }
  :deep(.arco-drawer-header) {
    background-color: rgb(232, 237, 250);
  }
</style>
